const Compiler = require("./Compiler");
const NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin");
const WebpackOptionsApply = require('./WebpackOptionsApply');

const webpack = (options)=>{
    let argv = process.argv.slice(2); //取出索引1之后的值
    let shellOptions =  argv.reduce((shellOptions,option)=>{
        let [key, value] = option.split("=");
        shellOptions[key.slice(2)] = value
        return shellOptions 
    },{})
    // 源码中使用webpack-merge专门用来合并配置文件
    let finalOptions = { ...options, ...shellOptions }; //将shell和webpack.config.js合并
    let compiler = new Compiler(finalOptions.context); //创建一个Compiler实例  
    compiler.options = finalOptions 

    new NodeEnvironmentPlugin().apply(compiler);//让compiler可以读文件和写文件

    //挂载配置文件里提供的所有的plugins
    if(options.plugins && Array.isArray(options.plugins)){
        for (const plugin of options.plugins) {
            plugin.apply(compiler)
        }
    }
    //初始化选项,挂载内置插件
    new WebpackOptionsApply().process(finalOptions,compiler);

    return compiler;

}
exports = module.exports = webpack